/**
 * Created by Administrator on 2018/7/27 0027.
 */

layui.use(['form', 'layer'], function () {

    // 操作对象
    var form = layui.form,
        layer = layui.layer,
        $ = layui.jquery;

    var token = $('#token').val();

    // 验证
    form.verify({
        account: function (value) {
            if (value == "") {
                return "请输入用户名";
            }
        },
        password: function (value) {
            if (value == "") {
                return "请输入密码";
            }
        },
        code: function (value) {
            if (value == "") {
                return "请输入验证码";
            }
        }
    });

    // 提交监听



    form.on('submit(sub)', function (data) {
        var data = data.field;
        doLogin(data);
    });

    $(document).keyup(function(event) {
        if(event.keyCode == 13) {
            var data = {};
            data.username = $("input[ name='username' ]").val();
            data.password = $("input[ name='password' ]").val();
            data._token = token;
            doLogin(data);
        }
    });

    function doLogin(data){
        $.ajax({
            url: '/dologin',          //  登录
            type: 'POST',
            data: data,
            timeout: 1000,
            dataType: 'json',
            success: function (data, textStatus, jqXHR) {

                if (data.error_code == 0) {
                    layer.msg('登陆成功',{
                        time: 2000, //2s后自动关闭
                        end:function(e){
                            location.href = "/home"
                        }
                    });
                } else {
                    layer.alert('账号或密码不对，请从新登陆？');
                }
            }
        })
    }
});